package com.atguigu.gmall.common.config;



import com.atguigu.gmall.common.BloomTask;
import com.atguigu.gmall.common.SkuBloomTask;
import com.atguigu.gmall.common.constants.RedisConst;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;

import org.redisson.config.Config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2024/9/17 1:00
 */
@Slf4j
@AutoConfigureAfter(RedisAutoConfiguration.class)//必须在redis自动配置后再进行
@Configuration
public class AppRedissonConfig {
    @Autowired(required = false)
    List<BloomTask> bloomTasks;

    @Bean
    public RedissonClient redissonClient(RedisProperties redisProperties) {
        Config config = new Config();
        config.useSingleServer().
                setAddress("redis://"+redisProperties.getHost() +":"+ redisProperties.getPort()).
                setPassword(redisProperties.getPassword());

        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }
    @Bean
    public RBloomFilter<Object> skuBloomFilter(RedissonClient redissonClient){
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConst.BLOOM_SKU_ID);
        if (bloomFilter.isExists()){
            log.info("redis中布隆过滤器存在...");
            //有这个布隆过滤器
            return bloomFilter;
        }else {
            //没有这个布隆过滤器
            log.info("redis正在创建布隆过滤器...");
            bloomFilter.tryInit(500000L, 0.00001);
            //初始化布隆过滤器
            for (BloomTask bloomTask : bloomTasks) {
                if (bloomTask instanceof SkuBloomTask){
                    bloomTask.initSkuIdBloom(bloomFilter);
                }
            }
        }


        return bloomFilter;
    }
}
